package com.demo.lifeinfo.common.publish;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.demo.lifeinfo.R;
import com.demo.lifeinfo.app.XBaseActivity;
import com.demo.lifeinfo.config.Constant;
import com.demo.lifeinfo.entity.News;
import com.demo.lifeinfo.entity.User;
import com.demo.lifeinfo.model.GlideApp;
import com.demo.lifeinfo.model.XPImageLoader;
import com.flyco.roundview.RoundTextView;
import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;

/**
 * created by Raymond
 * on 2019-04-28
 */
public class PublishActivity extends XBaseActivity {


    BaseQuickAdapter<String, BaseViewHolder> adapter;
    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.toolbar_right_btn)
    RoundTextView toolbarRightBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;
    @BindView(R.id.editText)
    EditText editText;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    List<String> paths;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_tag)
    TextView tvTag;
    int typeValue = 0;
    String tag = "无";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish;
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).transparentStatusBar().init();
        paths = new ArrayList<>();
        paths.add("add");
        toolbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new XPopup.Builder(PublishActivity.this)
                        .asConfirm("提示！", "是否放弃编辑？", new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                finish();
                            }
                        }).show();
            }
        });
        appBarLayout.setBackgroundResource(R.color.colorPrimary);
        textView3.setText("编辑");
        toolbarRightBtn.setVisibility(View.VISIBLE);
        toolbarRightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgressDialog();
                uploadFiles(paths);
            }
        });
        adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_publish_img) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                helper.addOnClickListener(R.id.imgView);
                helper.addOnClickListener(R.id.btn_delet);

                ImageView imageView = helper.getView(R.id.imgView);
                if (item.equals("add")) {
                    helper.setVisible(R.id.btn_delet, false);
                    GlideApp.with(PublishActivity.this).load(R.drawable.ic_add).into(imageView);
                } else {
                    helper.setVisible(R.id.btn_delet, true);
                    GlideApp.with(PublishActivity.this).load(item).centerCrop().into(imageView);
                }
            }
        };
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.btn_delet) {
                    paths.remove(position);
                    adapter.notifyItemRemoved(position);
                } else {
                    if (paths.size() < 6 && (adapter.getData().size() - 1) == position) {
                        openAblum();
                    } else {
                        new XPopup.Builder(PublishActivity.this)
                                .asImageViewer((ImageView) view, adapter.getItem(position), -1, -1, 50, false, new XPImageLoader())
                                .show();
                    }
                }
            }
        });
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setAdapter(adapter);
        adapter.setNewData(paths);
    }

    @Override
    protected void initData() {

    }


    @SuppressLint("NewApi")
    private void openAblum() {
        Album.image(this)
                .multipleChoice()
                .selectCount(6)
                .camera(false)
                .columnCount(4)
                .widget(Widget.newLightBuilder(this)
                        .statusBarColor(this.getColor(R.color.colorPrimary))
                        .toolBarColor(this.getColor(R.color.colorPrimary))
                        .build())
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        for (int i = 0; i < paths.size(); i++) {
                            if (paths.get(i).equals("add")) {
                                paths.remove(i);
                            }
                        }
                        if (result.size() + paths.size() > 6) {
                            showError("最多选择六张图");
                            return;
                        }
                        for (AlbumFile file : result) {
                            paths.add(file.getPath());
                        }
                        if (paths.size() < 6) {
                            paths.add("add");
                        }
                        adapter.setNewData(paths);

                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {

                    }
                })
                .start();

    }

    private void uploadFiles(List<String> files) {
        if (files.size() < 2) {
            publish(null, editText.getText().toString());
            return;
        }
        if (files.get(files.size() - 1).equals("add")) {
            files.remove(files.size() - 1);
        }
        String[] fs = new String[files.size()];
        for (int i = 0; i < files.size(); i++) {
            fs[i] = files.get(i);
        }
        BmobFile.uploadBatch(fs, new UploadBatchListener() {
            @Override
            public void onSuccess(List<BmobFile> list, List<String> list1) {

                if (list1.size() == fs.length) {//成功
                    publish(list1, editText.getText().toString());
                } else {

                }

            }

            @Override
            public void onProgress(int i, int i1, int i2, int i3) {

            }

            @Override
            public void onError(int i, String s) {
                dimssProgressDialog();
                showError("code:" + i + "--msg" + s);
            }
        });

    }

    private void publish(List<String> imgs, String text) {
        if (TextUtils.isEmpty(text)) {
            showError("请编辑内容！");
            dimssProgressDialog();
            return;
        }
        News news = new News();
        if (imgs != null && imgs.size() > 0) {

            news.setImgs(imgs);
        }
        news.setAuthor(BmobUser.getCurrentUser(User.class));
        news.setContent(text);

        if (typeValue == 0) {
            news.setType(Constant.TYPE_FUNNY);
        } else {
            news.setType(typeValue);
        }
        news.setTag(tag);
        news.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                dimssProgressDialog();
                if (e == null) {
                    showError("成功");
                    finish();
                } else {
                    showError("失败");
                    Log.e("xiaoqiang", e.getErrorCode() + "--msg" + e.getMessage());
                }
            }
        });
    }


    @OnClick(R.id.btn_type)
    public void onViewClicked() {

        new XPopup.Builder(this).asBottomList("类型", new String[]{"问题", "趣事", "其他"}, new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                tvType.setText(text);
                Log.e("xiaoqiang", position + "???/");
                typeValue = position + 1;
            }
        }).show();
    }

    @OnClick(R.id.btn_tag)
    public void onViewClicked2() {

        new XPopup.Builder(this).asBottomList("标签", getResources().getStringArray(R.array.hobbys), new OnSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                tag = text;
                tvTag.setText(text);
            }
        }).show();
    }

    @Override
    public void onBackPressedSupport() {
        new XPopup.Builder(PublishActivity.this)
                .asConfirm("提示！", "是否放弃编辑？", new OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        finish();
                    }
                }).show();
    }
}
